﻿#pragma once

#include"HashTable.h"

namespace aj
{
	template<class K , class V>
	class unordered_map
	{
	public:
		struct MapKeyOfT
		{
			const K& operator()(const pair<K, V>& kv)
			{
				return kv.first;
			}
		};
	public:
		typedef typename hash_bucket::hash_table<K, pair<const K, V>, MapKeyOfT, HashFunc<K>>::iterator iterator;
		typedef typename hash_bucket::hash_table<K, pair<const K, V>, MapKeyOfT, HashFunc<K>>::const_iterator const_iterator;

		pair<iterator,bool> insert(const pair<K, V>& kv)
		{
			return _ht.Insert(kv);
		}

		iterator begin()
		{
			return _ht.begin();
		}

		iterator end()
		{
			return _ht.end();
		}

		const_iterator begin()const
		{
			return _ht.begin();
		}

		const_iterator end()const
		{
			return _ht.end();
		}

		V& operator[](const K& key)
		{
			auto tmp = _ht.Insert(make_pair(key,V()));
			return tmp.first->second;
		}

		const V& operator[](const K& key)const
		{
			auto tmp = _ht.Insert(make_pair(key, V()));
			return tmp.first->second;
		}

		bool erase(const K& key)
		{
			return _ht.Erase(key);
		}

		iterator find(const K& key)
		{
			return _ht.Find(key);
		}

		void clear()
		{
			_ht.Clear();
		}

		size_t size()
		{
			return _ht.Size();
		}

		void swap(unordered_map<K,V>& um)
		{
			_ht.Swap(um._ht);
		}

	private:
		// unordered_map中K是不能被改变的
		hash_bucket::hash_table <K, pair<const K, V>, MapKeyOfT , HashFunc<K>> _ht;
	};
	void test_unordered_map1()
	{
		unordered_map<int, int> um;
		um.insert(make_pair(1, 1));
		um.insert(make_pair(2, 2));
		um.insert(make_pair(3, 3));
		um.insert(make_pair(4, 4));

		unordered_map<int, int>::iterator it = um.begin();
		while (it != um.end())
		{
			cout << it->first << ' ' << it->second << endl;
			++it;
		}
	}

	void test_unordered_map2()
	{
		unordered_map<string, string> dict;
		dict.insert(make_pair("sort", "排序"));
		dict.insert(make_pair("insert", "插入"));
		dict.insert(make_pair("string", "字符串"));


		for (auto& kv : dict)
		{
			// kv.first += 'x';
			kv.second += 'x';

			cout << kv.first << ":" << kv.second << endl;
		}
		cout << endl;

		string arr[] = { "香蕉", "甜瓜","苹果", "西瓜", "苹果", "西瓜", "苹果", "苹果", "西瓜", "苹果", "香蕉", "苹果", "香蕉" };
		unordered_map<string, int> count_map;
		for (auto& e : arr)
		{
			count_map[e]++;
		}

		for (auto& kv : count_map)
		{
			cout << kv.first << ":" << kv.second << endl;
		}
		cout << endl;
	}
}